﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Windows.Threading;
using System.ComponentModel;

namespace ShahyadS.TFSBuildInspectionModel
{
	public class SafeObservableCollection<T> : ObservableCollection<T>, IList<T>
	{
		public override event NotifyCollectionChangedEventHandler CollectionChanged;
		protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
		{
			NotifyCollectionChangedEventHandler collectionChanged = this.CollectionChanged;
			if (collectionChanged != null)
			{
				foreach (NotifyCollectionChangedEventHandler nh in collectionChanged.GetInvocationList())
				{
					DispatcherObject dispObj = nh.Target as DispatcherObject;
					ISynchronizeInvoke syncInvoke = nh.Target as ISynchronizeInvoke;
					if (dispObj != null)
					{
						Dispatcher dispatcher = dispObj.Dispatcher;
						if (dispatcher != null && !dispatcher.CheckAccess())
						{
							dispatcher.BeginInvoke(
								(Action)(() => nh.Invoke(this,
									new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset))),
								DispatcherPriority.DataBind);
							continue;
						}
					}
					else if (syncInvoke != null && syncInvoke.InvokeRequired)
					{
						syncInvoke.BeginInvoke((Action)(() => { nh.Invoke(this, e); }), null);
						continue;
					}
					nh.Invoke(this, e);
				}
			}
		}

	}
}
